<template>
  <view class="muyu-container">
    <view class="header">
      <text class="title">电子木鱼</text>
      <text class="subtitle">积德行善，心灵净化</text>
    </view>

    <view class="merit-counter">
      <text class="merit-text">功德值: {{ meritCount }}</text>
      <text class="today-merit">今日功德: {{ todayMeritCount }}</text>
    </view>

    <view class="muyu-wrapper">
      <image
        class="muyu-image"
        :class="{ 'tap-animation': isAnimating }"
        src="/static/muyu/muyu.png"
        mode="aspectFit"
        @tap="tapMuyu"
      ></image>

      <view class="merit-popup" v-if="showMeritPopup" :style="meritPopupStyle">
        <text class="merit-popup-text">功德+1</text>
      </view>
    </view>

    <view class="stats-section">
      <view class="stat-item">
        <text class="stat-label">总敲击次数</text>
        <text class="stat-value">{{ totalTaps }}</text>
      </view>
      <view class="stat-item">
        <text class="stat-label">连续天数</text>
        <text class="stat-value">{{ consecutiveDays }}</text>
      </view>
    </view>

    <view class="settings">
      <button class="setting-btn" @tap="toggleSound">
        {{ isSoundOn ? '关闭音效' : '开启音效' }}
      </button>
      <button class="setting-btn" @tap="resetMerit">重置功德</button>
    </view>
      <button class="setting-btn" style="margin-top: 20px;" open-type="share">分享给好友</button>
  </view>
  <FloatButton />
</template>

<script>
import FloatButton from '@/components/FloatButton.vue'
import { getShareAppMessageConfig, getShareTimelineConfig } from '../../utils/share.js'

export default {
  components: {
    FloatButton
  },
  data() {
    return {
      meritCount: 0,
      todayMeritCount: 0,
      totalTaps: 0,
      consecutiveDays: 0,
      lastTapDate: '',
      isSoundOn: true,
      isAnimating: false,
      showMeritPopup: false,
      meritPopupStyle: {
        top: '0px',
        left: '0px'
      },
      audioContext: null
    }
  },

  onLoad() {
    this.loadUserData()
    this.initAudio()
    this.checkConsecutiveDays()
  },
  // 分享到聊天
  onShareAppMessage() {
    return getShareAppMessageConfig({
      title: '喝水记录打卡 - 安记录丨工具舱',
      path: '/pages-sub/drink/index',
      imageUrl: '/static/share-img.png'
    })
  },
  // 分享到朋友圈
  onShareTimeline() {
    return getShareTimelineConfig({
      title: '喝水记录打卡 - 安记录丨工具舱',
      imageUrl: '/static/share-img.png'
    })
  },

  methods: {
    tapMuyu(e) {
      // 增加功德值
      this.meritCount++
      this.todayMeritCount++
      this.totalTaps++
      // 连续音效，打断效果
      if (this.audioContext) {
        this.audioContext.stop()
      }

      // 播放音效
      if (this.isSoundOn && this.audioContext) {
        this.audioContext.play()
      }

      // 触发动画
      this.isAnimating = true
      setTimeout(() => {
        this.isAnimating = false
      }, 200)

      // 显示功德+1的弹出效果
      const touchX = e.touches[0].clientX
      const touchY = e.touches[0].clientY

      this.meritPopupStyle = {
        left: `${touchX - 20}px`,
        top: `${touchY - 40}px`
      }

      this.showMeritPopup = true
      setTimeout(() => {
        this.showMeritPopup = false
      }, 800)

      // 保存数据
      this.saveUserData()
    },

    initAudio() {
      // 创建音频上下文
      this.audioContext = uni.createInnerAudioContext()
      this.audioContext.src = '/static/muyu/muyu.mp3'
      this.audioContext.autoplay = false
    },

    toggleSound() {
      this.isSoundOn = !this.isSoundOn
      uni.showToast({
        title: this.isSoundOn ? '音效已开启' : '音效已关闭',
        icon: 'none'
      })
    },

    resetMerit() {
      uni.showModal({
        title: '确认重置',
        content: '确定要重置所有功德值吗？',
        success: res => {
          if (res.confirm) {
            this.meritCount = 0
            this.todayMeritCount = 0
            this.saveUserData()
            uni.showToast({
              title: '功德已重置',
              icon: 'success'
            })
          }
        }
      })
    },

    loadUserData() {
      try {
        const userData = uni.getStorageSync('muyuData')
        if (userData) {
          const data = JSON.parse(userData)
          this.meritCount = data.meritCount || 0
          this.totalTaps = data.totalTaps || 0
          this.consecutiveDays = data.consecutiveDays || 0
          this.lastTapDate = data.lastTapDate || ''

          // 检查是否是今天的数据
          const today = this.getFormattedDate(new Date())
          if (data.lastTapDate === today) {
            this.todayMeritCount = data.todayMeritCount || 0
          } else {
            this.todayMeritCount = 0
          }
        }
      } catch (e) {
        console.error('加载木鱼数据失败', e)
      }
    },

    saveUserData() {
      try {
        const today = this.getFormattedDate(new Date())
        const userData = {
          meritCount: this.meritCount,
          todayMeritCount: this.todayMeritCount,
          totalTaps: this.totalTaps,
          consecutiveDays: this.consecutiveDays,
          lastTapDate: today
        }

        uni.setStorageSync('muyuData', JSON.stringify(userData))
      } catch (e) {
        console.error('保存木鱼数据失败', e)
      }
    },

    checkConsecutiveDays() {
      const today = this.getFormattedDate(new Date())

      if (!this.lastTapDate) {
        // 首次使用
        this.consecutiveDays = 1
        this.lastTapDate = today
      } else if (this.lastTapDate === today) {
        // 今天已经敲过
        // 不做任何改变
      } else {
        // 检查是否是连续的
        const lastDate = new Date(this.lastTapDate)
        const currentDate = new Date(today)

        // 计算日期差
        const timeDiff = currentDate.getTime() - lastDate.getTime()
        const dayDiff = Math.floor(timeDiff / (1000 * 3600 * 24))

        if (dayDiff === 1) {
          // 连续天数
          this.consecutiveDays++
        } else if (dayDiff > 1) {
          // 中断了，重新开始计数
          this.consecutiveDays = 1
        }

        this.lastTapDate = today
        this.todayMeritCount = 0
      }

      this.saveUserData()
    },

    getFormattedDate(date) {
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      return `${year}-${month}-${day}`
    }
  }
}
</script>

<style>
.muyu-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 40rpx;
  min-height: 100vh;
  background-color: #f8f3e9;
}

.header {
  text-align: center;
  margin-bottom: 40rpx;
}

.title {
  font-size: 48rpx;
  font-weight: bold;
  color: #8b4513;
}

.subtitle {
  font-size: 28rpx;
  color: #a0522d;
  margin-top: 10rpx;
  display: block;
}

.merit-counter {
  background-color: rgba(139, 69, 19, 0.1);
  padding: 20rpx 40rpx;
  border-radius: 20rpx;
  margin-bottom: 60rpx;
  text-align: center;
}

.merit-text {
  font-size: 36rpx;
  font-weight: bold;
  color: #8b4513;
}

.today-merit {
  font-size: 28rpx;
  color: #a0522d;
  margin-top: 10rpx;
  display: block;
}

.muyu-wrapper {
  position: relative;
  width: 400rpx;
  height: 400rpx;
  margin: 40rpx 0;
}

.muyu-image {
  width: 100%;
  height: 100%;
  transition: transform 0.1s ease;
}

.tap-animation {
  transform: scale(0.95);
}

.merit-popup {
  position: absolute;
  animation: float-up 0.8s ease-out;
  opacity: 0;
}

.merit-popup-text {
  color: #ff6b00;
  font-size: 36rpx;
  font-weight: bold;
}

@keyframes float-up {
  0% {
    transform: translateY(0);
    opacity: 1;
  }
  100% {
    transform: translateY(-80rpx);
    opacity: 0;
  }
}

.stats-section {
  display: flex;
  justify-content: space-around;
  width: 100%;
  margin: 40rpx 0;
}

.stat-item {
  text-align: center;
  padding: 20rpx;
  background-color: rgba(139, 69, 19, 0.1);
  border-radius: 16rpx;
  width: 45%;
}

.stat-label {
  font-size: 28rpx;
  color: #a0522d;
  display: block;
}

.stat-value {
  font-size: 36rpx;
  font-weight: bold;
  color: #8b4513;
  margin-top: 10rpx;
  display: block;
}

.settings {
  margin-top: 40rpx;
  width: 100%;
  display: flex;
  justify-content: space-around;
}

.setting-btn {
  background-color: #8b4513;
  color: white;
  font-size: 28rpx;
  padding: 10rpx 30rpx;
  border-radius: 30rpx;
  width: 45%;
}
</style>
